<?php
include_once '../Controller/ConnectFB.php';
require '../Controller/Config.php';
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

$pollId = $_POST['report'];
//echo $_POST["report"]."<br>";
function mean($x) {
$summation = 0;
$values = 0;
    if(isset($x)){
    foreach ($x as $value) {
        if (is_numeric($value)) {
            $total = $total + $value;
            $values++;
        }
    }
    if($values!=0){
        $mean = $total/$values;
        return $mean;
    }
    }
    
}        

function standard_deviation($x) {
$summation = 0;
$values = 0;
if(isset($x)){
    foreach ($x as $value) {
        if (is_numeric($value)) {
            $summation = $summation + $value;
            $values++;
        }
    }
    if($values!=0){
        $mean = $summation/$values;
    foreach ($x as $value) {
        if (is_numeric($value)) {
            $ex2 = $ex2 + ($value*$value);
        }
    }
    $rawsd = ($ex2/$values) - ($mean * $mean);
    $sd = sqrt($rawsd);
    return $sd;
    }
}
}

?>
<!DOCTYPE html>
<html>
    <head>
        <link rel="shortcut icon" href="../icon/favicon.ico"/>
        <link rel="stylesheet" href="../css/myStyle.css" type="text/css" />
        <script type="text/javascript" src="../js/jquery.fixedMenu.js"></script>
   <link rel="stylesheet" type="text/css" href="../css/fixedMenu_style2.css" />
       <!--[if lt IE 9]><script language="javascript" type="text/javascript" src="../js/excanvas.js"></script><![endif]-->
   <script type="text/javascript" src="../js/jquery.min.js"></script>
        <script type="text/javascript" src="../js/jquery.jqplot.js"></script>
        <script type="text/javascript" src="../js/jquery.jqplot.min.js"></script>
        <script type="text/javascript" src="../js/jqplot.cursor.min.js"></script>
        <script type="text/javascript" src="../js/jqplot.dragable.min.js"></script>
        <script type="text/javascript" src="../js/jqplot.trendline.min.js"></script>
        <script type="text/javascript" src="../js/jqplot.categoryAxisRenderer.min.js"></script>
        <script type="text/javascript" src="../js/jqplot.barRenderer.min.js"></script>
        <script type="text/javascript" src="../js/jqplot.pieRenderer.min.js"></script>
        <script type="text/javascript" src="../js/jqplot.canvasAxisLabelRenderer.min.js"></script>
        <script type="text/javascript" src="../js/jquery-ui.min.js"></script>
         <script type="text/javascript" src="../js/jqplot.pointLabels.min.js"></script>
    <script class="include" type="text/javascript" src="../js/jqplot.canvasTextRenderer.min.js"></script>
    <script class="include" type="text/javascript" src="../js/jqplot.canvasAxisTickRenderer.min.js"></script>



    <script type="text/javascript" src="../js/jqplot.dateAxisRenderer.min.js"></script>
    <script type="text/javascript" src="../js/jqplot.highlighter.min.js"></script>
    <script type="text/javascript" src="../js/jqplot.enhancedLegendRenderer.min.js"></script>
        <link rel="stylesheet" type="text/css" hrf="../css/jquery.jqplot.min.css" />
        <link rel="stylesheet" type="text/css" href="../css/jquery.jqplot.css"/>

    </head>

<style>
body
{
        background-image:url('../images/bg.jpg');
        background-repeat:repeat-x;
        background-color:#f8e3b7;
 
}
</style>
    </head>
<body>

<table border="0" width="80%" height="650px" align="center" cellpadding="5" cellspacing="1" bgcolor="#404040">
  <tr height="30px">
    <td colspan="2" bgcolor="#ffffff">
        <div class="menu">
        <ul align="left">
            <table align="left" border="0">
                <tr>
                    <td>
                        <a href="../Interface/MenuHome.php">Home</a>
                    </td>
                </tr>
            </table>


            <table align="left" border="0">
                <tr>
                    <td>
                <a href="../Interface/MenuCreatePoll.php">Create Poll</a>
                    </td>
                </tr>
            </table>

            <table align="left" border="0">
                <tr>
                    <td>
                <a href="../Interface/MenuAnswer.php">Answer Poll</a>
                    </td>
                </tr>
            </table>
            
            <table align="left" border="0">
                <tr>
                    <td>
                <a href="../View/Compensation.php">Compensation</a>
                    </td>
                </tr>
            </table>
            
            <table align="left" border="0">
                <tr>
                    <td>
                <a href="../View/Statistics.php">Statistics</a>
                    </td>
                </tr>
            </table>

           <table align="left" border="0">
                <tr>
                    <td>
                <a href="../Interface/MenuAbout.php">About</a>
                    </td>
                </tr>
            </table>

            <table align="left" border="0">
                <tr>
                    <td>
                <a href="../Interface/MenuContact.php">Contact</a>
                    </td>
                </tr>
            </table>
        </ul>

        <ul align="right"> 
            <?php if($fb_user){?>
               <table align="right" border="0" >
                   <tr>
                       <td>
                           <img width="25px" higth="25px"  src="https://graph.facebook.com///<?php echo $fb_user?>/picture">
                       </td>
                       <td>
                       <font color="white" size="2" align="left"><?php echo $_SESSION['strName'] ?></font>
                <a href="<?php echo $logoutUrl?>" >Logout</a>
                </table>
                <?php }else{?>
                <table align="right" border="0" >
                    <tr>
                        <td>
                    <a href="javascript:popup('<?php echo $loginUrl?>','',500,350);">Login with Facebook</a>
                        </td>
                       </tr>
                   </table>
                <?php } ?>
              </ul> 
    </div>
    </td>
  </tr>
  <tr>
    <td colspan="2" bgcolor="#ffffff" align="left" valign="top">
        <?php
        $query_poll = "SELECT * FROM poll WHERE poll_id = ".$pollId;
        $rs1 = mysql_query($query_poll) or die("Error SQL[ ".$query_poll." ] ".mysql_error());

        echo <<<HTML
            <form name="pollFrm" id="pollFrm" method="post" action="../Controller/SaveAnswerAction.php" >
HTML;

        $i=0;
        $inputType = "";
        $arrData = array();
        $arrScale = array();
        $datatograph = array();
        //fetch poll by created_by AND poll_id
        while($obj1 = mysql_fetch_array($rs1)){

            echo "<b>ชื่อแบบสอบถาม : ".$obj1['poll_title']."</b>";
            echo "<br />";
            echo "<b>รายละเอียดเกียวกับแบบสอบถาม : ".$obj1['poll_desc']."</b>";
            $pollDetial = $obj1['poll_desc'];
            echo "<br /><br />";

            $arrData['poll_title'] = $obj1['poll_title'];
            $arrData['poll_desc'] = $obj1['poll_desc'];

            $query_question = "SELECT * FROM question WHERE poll_id = ".$obj1['poll_id'];
            $rs2 = mysql_query($query_question) or die("Error SQL[ ".$query_question." ] ".mysql_error());
//echo $query_question;
            //fetch question by poll_id
            
            while($obj2 = mysql_fetch_array($rs2)){
                $datatograph = array();
                $datatotable = array();
                echo '<input type="hidden" name="questionId[]" value="'.$obj2['question_id'].'" />';
                echo "<b>".($i+1).". ".$obj2['question_value']."</b>";
                echo "<br />";


//                if($obj2['question_type']==1){
//                    $inputType = '<input type="radio" name="data'.$i.'[]" />';
//                }else if($obj2['question_type']==2){
//                    $inputType = '<input type="checkbox" name="data'.$i.'[]" />';
//                }else if($obj2['question_type']==3){
                if($obj2['question_type']==3){
//                    echo $obj2['question_id'];
//                  //getvaluetype3
                    
                    
                    //checkstatcompute
                    $qchktype3 = "SELECT compute.cal_stat FROM
                                    compute where poll_id = '".$pollId."' and question_id = '".$obj2['question_id']."'";
                    $rstype3 = mysql_query($qchktype3) or die("Error SQL[ ".$qchktype3." ] ".mysql_error());
                    $fetchtype = mysql_fetch_array($rstype3);
//                    echo $qchktype3;
                    $p=1;
                    $g = 1;
                    
                    if($fetchtype['cal_stat']==1){
                        $qgetval = "SELECT * FROM answer WHERE poll_id = '".$pollId."' and question_id = '".$obj2['question_id']."'";
                        $rsgetval = mysql_query($qgetval) or die("Error SQL[ ".$qgetval." ] ".mysql_error());
//                        echo $qgetval;
                        while($datafetch = mysql_fetch_array($rsgetval)){
                            if($datafetch['answer_value']!=null){
                                        $datatocom[$p] = $datafetch['answer_value'];
                                        $p++;
                            }
                        }
                        echo "<br/>";
                        if(count($datatocom)!=0){
                        if(max($datatocom)<=10){
                            $rank_each = 0;
                        }else{
                            $rank_each = (max($datatocom)-min($datatocom))/10;
                        }
                        
//                        echo $rank_each;
                        
                        
                        $rank = min($datatocom);
//                        echo $rank;
                        $rank_to = $rank+$rank_each;
                        }else{
                            $rank = 1;
                            $rank_each = 0;
                            $rank_to = 1;
                        }
                        $count_rank = 1;
                        for($count_rank;$count_rank<=10;$count_rank++){
                            
                            $qgetrankval = "SELECT COUNT(*) AS val FROM answer WHERE poll_id = '".$pollId."' and question_id = '".$obj2['question_id']."' AND answer_value BETWEEN ".$rank." AND ".$rank_to."";
//                            echo $qgetrankval."<br/>";
                            $rscount_rank = mysql_query($qgetrankval) or die("Error SQL[ ".$qgetrankval." ] ".mysql_error());
                            $rscount_rank_fetch=mysql_fetch_array($rscount_rank);
                            $datatograph[$g] = $rscount_rank_fetch['val'];
                            $datatotable[$g] = $rank."-".$rank_to;
                            
                            $rank = $rank+$rank_each+1;
                            $rank_to = $rank+$rank_each;
//                            echo $count_rank."  ".$qgetrankval."<br/>";
                            $g++;
                        }
//                        print_r($datatograph);
//                        echo "<br/>";
//                        print_r($datatotable);
                        ?>
                                    <font size="5" align="left">&nbsp;&nbsp;&nbsp;&nbsp;<?php echo "Mean : " . number_format(mean($datatocom), 2, '.', ''); ?></font><br/>
                                    <font size="5" align="left">&nbsp;&nbsp;&nbsp;&nbsp;<?php echo "SD : " . number_format(standard_deviation($datatocom), 2, '.', ''); ?></font>
                                  
                                    
                        <?php
                    }else{
                        $qgetval = "SELECT DISTINCT COUNT(answer_value) AS val,answer_value FROM answer WHERE poll_id = '".$pollId."' and question_id = '".$obj2['question_id']."' AND answer_value<>'' GROUP BY answer_value ORDER BY val DESC LIMIT 10";
                        $rsgetval = mysql_query($qgetval) or die("Error SQL[ ".$qgetval." ] ".mysql_error());
//                        echo $qgetval;
                        while($fetchval = mysql_fetch_array($rsgetval)){
                                $datatograph[$p] = $fetchval['val'];
                                $datatotable[$p] = $fetchval['answer_value'];
                                $p++;
                        }
//                        print_r($datatograph);
//                        echo "<br/>";
//                        print_r($datatotable);
//                         $inputType = "<textarea style='margin-top:20px; margin-left:20px; width:600px; height:300px;' rows='20' name='data'.$i.'[]' readonly>".$valtotext."</textarea><br/>";
                        
                    }
//                   
                }else if($obj2['question_type']==4){
                    $inputType = 'scale';
                    $inputTypeScale = '';
                }


                $query_choice = "SELECT
                                choice.choice_value,
                                Count(answer.answer_value) AS counter,
                                choice.question_type,
                                choice.choice_id
                                FROM
                                answer
                                RIGHT JOIN choice ON answer.answer_value = choice.choice_value
                                WHERE choice.question_id = ".$obj2['question_id']." AND choice.poll_id = ".$obj1['poll_id']."
                                GROUP BY choice.choice_value ORDER BY choice.question_id";
//                echo $query_choice;
                $rs3 = mysql_query($query_choice) or die("Error SQL[ ".$query_choice." ] ".mysql_error());
                $j=0;
                $k=0;

                $arrScale = array();
                $arrScaleLabel = array();

                //fetch choice by question_id AND poll_id
                
                
                while($obj3 = mysql_fetch_array($rs3)){

                    if($inputType!="scale"){
                        if($obj2['question_type']==3){
                            echo $inputType;
                            echo "<br />";

                            $arrData[$i][$obj2['question_value']][$k] = $inputType;
                            $k++;
                        }else{
                            //value to graph

                            $datatograph[$obj3['choice_value']] = $obj3['counter'];


//                            echo $inputType." ".$obj3['choice_value'];
//                            echo "<br />";

                            $arrData[$i][$obj2['question_value']][$k] = $inputType." ".$obj3['choice_value'];
                            $k++;
                        }
                    }else{

                        $arrScale[$j] = $obj3['choice_value'];


                        $query_option = "SELECT * FROM option_scale WHERE choice_id = ".$obj3['choice_id'];
                        $rs4 = mysql_query($query_option) or die("Error SQL[ ".$query_option." ] ".mysql_error());

                        //fetch option_scale by choice_id
                        while($obj4 = mysql_fetch_array($rs4)){

                                $arrScaleLabel[$j] = $obj4['option_value'];

                                $arrData[$i][$obj2['question_value']][$obj3['choice_value']] = $obj4['option_value'];

                        }

                        if($j==1){
                                
                                for($loop = $arrScale[0]; $loop <= $arrScale[1]; $loop++){
                                   $qfre = "SELECT COUNT(*) AS fre FROM answer
                                    WHERE poll_id = '".$pollId."' and question_id = '".$obj2['question_id']."' AND answer_value = '".$loop."'";
//                                   echo $qfre;
                                    $rsfre = mysql_query($qfre) or die("Error SQL[ ".$qfre." ] ".mysql_error());
                                    $rsfree2=mysql_fetch_array($rsfre);
                                    $datatograph[$loop] = $rsfree2['fre'];
                                   
//                                        $inputTypeScale .= '<input type="radio" name="data'.$i.'[]" value="'.$loop.'" />';
                                }
                                $o=0;
                                $qcom = "SELECT * FROM answer 
                                        WHERE poll_id = '".$pollId."' and question_id = '".$obj2['question_id']."'";
                                $rscom = mysql_query($qcom) or die("Error SQL[ ".$qcom." ] ".mysql_error());
                                    while($datafetch = mysql_fetch_array($rscom)){
                                        $datatocom[$o] = $datafetch['answer_value'];
                                        $o++;
                                    }
                                    echo "<br/>";
                                    ?>
                                    <font size="5" align="left">&nbsp;&nbsp;&nbsp;&nbsp;<?php echo "Mean : " . number_format(mean($datatocom), 2, '.', ''); ?></font><br/>
                                    <font size="5" align="left">&nbsp;&nbsp;&nbsp;&nbsp;<?php echo "SD : " . number_format(standard_deviation($datatocom), 2, '.', ''); ?></font><br/>
                                  
                                    
                                    <?php
//                                 print_r($datatograph);
                                    
                                 $datatotable[$arrScale[0]] = $arrScaleLabel[0];
                                 $datatotable[$arrScale[1]] = $arrScaleLabel[1];
//                                echo $arrScaleLabel[0]." [".$arrScale[0]."] ".$inputTypeScale." [".$arrScale[1]."] ".$arrScaleLabel[1];
//                                echo "<br />";
                        }

                        $j++;
                    }
                }
                /*foreach ($datatograph as $key => $value)
                               echo "[".$key."     ".$value."]"."<br/>";
                $datatograph = array();
                echo "<br />";*/




              
//                             echo $obj2['question_value'];

                            $size = count($datatograph);
                            $z=0;


                   foreach ($datatograph as $key => $value){

                    /*$result = $result . '["' . $key . '",' . $value . ']';*/
                    $result[$obj2['question_id']] = $result[$obj2['question_id']] .'["'. $key . '",' . $value.']';
                     if($z != $size-1){
                      $result[$obj2['question_id']] = $result[$obj2['question_id']].',';
                         }
                         $z++;
                   }
                     $result[$obj2['question_id']] =  '['.$result[$obj2['question_id']].']';
                     
//                              echo $result[$obj2['question_id']];

                             ?>
                              <table>
                                  <tr>
                                      <td>  
                                          <div id="<?php echo $i;?>" style="margin-top:20px; margin-left:20px; width:600px; height:300px;"></div>
                                       </td>
                                       <td  valign="top" align="center">
                                           <table border="0" align="center">
                                           <?php
                                           if($obj2['question_type']==3||$obj2['question_type']==4){
                                           ?>
                                           
                                            <tr align="center" bgcolor="#ee974a" height="30px">
                                                <td>
                                                    <font color="#ffffff"><b>ค่าที่</b></font>
                                                </td>
                                                <td>
                                                    <font color="#ffffff"><b>ข้อมูล</b></font>
                                                </td>
                                            </tr>
                                            <?php
                                           }
                                           if($obj2['question_type']==3){
                                           for($u=1;$u<=count($datatotable);$u++){
                                               if($u%2==0){
                                                $bgcolor = "#ffffff";
                                                }else{
                                                    $bgcolor = "#f6d6a5";
                                                }
                                               ?>
                                            <tr bgcolor="<?php echo $bgcolor ?>" height="30px">
                                                <td align="center">
                                                    <font><?php echo $u ?></font>
                                                </td>
                                                <td>
                                                    <font><?php echo $datatotable[$u] ?></font>
                                                </td>
                                            </tr>
                                            <?php
                                            }
                                            ?>
                                            
                                           <?php
                                           }else if($obj2['question_type']==4){
                                           $t = 1;
                                            foreach ($datatotable as $key => $value){
                                               if($t%2==0){
                                                $bgcolor = "#ffffff";
                                                }else{
                                                    $bgcolor = "#f6d6a5";
                                                }
                                               ?>
                                            <tr bgcolor="<?php echo $bgcolor ?>" width="100px" height="30px">
                                                <td align="center">
                                                    <font><?php echo $key ?></font>
                                                </td>
                                                <td>
                                                    <font><?php echo $value ?></font>
                                                </td>
                                            </tr>
                                            <?php
                                            $t++;
                                           }
                                           }
                                           ?>
                                           </table>
                                       </td>
                                       </tr>
                              </table>
                                  
                             
                              <script>

                                   $(document).ready(function(){
                                     
//                                     var total = 0;
//                                $(open php tag echo data).map(function(){total += this[1];})
//                                myLabels = $.makeArray($(open php tag echo data).map(function(){return this[1] + "," + Math.round(this[1]/total * 100) + "%";}));
//                                 
                                    var plot2 = $.jqplot (<?php echo $i;?>, [<?php echo $result[$obj2['question_id']]; ?>],
                                    
                                    
                                    {

                                      seriesDefaults: {
                                        renderer: $.jqplot.<?php if($obj2['question_type']==3||$obj2['question_type']==4){echo "BarRenderer";}else{echo "PieRenderer";}?>,
                                        rendererOptions: {
                                          // Turn off filling of slices.
                                          fill: false,
//                                          dataLabels: myLabels,
//                                          dataLabelFormatString: "%d %s%%",
                                          showDataLabels: true,
                                          // Add a margin to seperate the slices.
                                          sliceMargin: 4,
                                          // stroke the slices with a little thicker line.
                                          lineWidth: 4,
                                        
                                        }
                                        
                                      }
                                      
                                          <?php if($obj2['question_type']==3||$obj2['question_type']==4){echo ",highlighter: {yvalues : 1 ,\n".
                                        "formatString:'<table class="."jqplot-highlighter"."><tr><td>ระดับ:</td><td>%s</td></tr><tr><td>จำนวน:</td><td>%s</td></tr></table>',\n".
                                        "show: true,\n".
                                          "sizeAdjust: 7.5\n".
                                         "},\n".
                                          "axesDefaults: {\n".
                                              "tickRenderer: $.jqplot.CanvasAxisTickRenderer,\n".
                                                  "tickOptions: {\n".
                                                    "angle: 0\n".
                                                  "}\n".
                                          "},\n".
                                          "axes: {\n".
                                            "xaxis: {\n".
                                              "renderer: $.jqplot.CategoryAxisRenderer,\n".
                                              "tickOptions: {\n".
                                                "labelPosition: 'middle'\n".
                                              "}\n".
                                            "},\n".
                                           " yaxis: {\n".
                                             " autoscale:true,\n".
                                             " tickRenderer: $.jqplot.CanvasAxisTickRenderer,\n".
                                              "tickOptions: {\n".
                                               " labelPosition: 'start'\n".
                                             " }\n".
                                            "}\n".
                                        "}";}else{echo " ";}?>

                                        <?php if($obj2['question_type']==4||$obj2['question_type']==3){echo ",title: 'กราฟแสดงความถี่'}";}else{echo ",legend: { show:true, location: 'e' }}";}?>
                                        
                                  );
                                });
                                </script>
                                
                             <?
                             
                           
                $i++;

            }
        }
        mysql_close();
        ?>

    <!--<img border="0" src="../images/Coming-Soon-logo.gif" alt="" width="500" height="500">-->
    </td>
  </tr>
</table>

</body>
</html>

